package io.github.talelin.latticy.controller.v1;

import io.github.talelin.core.annotation.GroupRequired;
import io.github.talelin.core.annotation.PermissionMeta;
import io.github.talelin.core.annotation.PermissionModule;
import io.github.talelin.latticy.common.util.PageUtil;
import io.github.talelin.latticy.dto.vip.VipOrderPaymentConfirmDTO;
import io.github.talelin.latticy.model.OrderDO;
import io.github.talelin.latticy.service.UnifiedOrderService;
import io.github.talelin.latticy.vo.OrderSimplifyVO;
import io.github.talelin.latticy.vo.PageResponseVO;
import io.github.talelin.latticy.vo.VipOrderPaymentConfirmVO;
import io.github.talelin.latticy.vo.VipOrderVO;
import io.github.talelin.autoconfigure.exception.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.Positive;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 统一订单管理控制器
 * 合并了原有的OrderController和VipOrderController功能
 * 现在所有订单都需要使用支付凭证交易
 */
@RestController
@RequestMapping("/v1/unified-order")
@Validated
@PermissionModule("统一订单管理")
public class UnifiedOrderController {

    @Autowired
    private UnifiedOrderService orderService;

    // ==================== 原有OrderController功能 ====================

    /**
     * 修改订单状态
     */
    @PutMapping("/status")
    @GroupRequired
    @PermissionMeta(value = "修改订单状态")
    public Map<String, Object> updateOrderStatus(
            @RequestParam(name = "id") @Positive Integer id,
            @RequestParam(name = "status") @Min(value = 0) Integer status
    ) {
        orderService.changeOrderStatus(id, status);
        Map<String, Object> result = new HashMap<>();
        result.put("message", "订单状态更新成功");
        return result;
    }

    /**
     * 获取订单详情
     */
    @GetMapping("/{id}/detail")
    @GroupRequired
    @PermissionMeta("查询订单详情")
    public OrderDO getOrderDetail(@PathVariable(value = "id") @Positive(message = "{id.positive}") Integer id) {
        OrderDO order = orderService.getById(id);
        if (order == null) {
            throw new NotFoundException(110000);
        }
        return order;
    }

    /**
     * 获取订单分页列表
     */
    @GetMapping("/page")
    @GroupRequired
    @PermissionMeta("查询订单分页")
    public PageResponseVO<OrderSimplifyVO> getOrderPage(
            @RequestParam(name = "count", required = false, defaultValue = "10")
            @Min(value = 1, message = "{page.count.min}")
            @Max(value = 30, message = "{page.count.max}") Integer count,
            @RequestParam(name = "page", required = false, defaultValue = "0")
            @Min(value = 0, message = "{page.number.min}") Integer page
    ) {
        com.baomidou.mybatisplus.core.metadata.IPage<OrderDO> iPage = orderService.getOrderByPage(count, page);
        List<OrderSimplifyVO> orderSimplifyVOList = orderService.convertFromDO(iPage.getRecords());
        return PageUtil.build(iPage, orderSimplifyVOList);
    }

    /**
     * 搜索订单
     */
    @GetMapping("/search")
    @GroupRequired
    @PermissionMeta("搜索订单")
    public PageResponseVO<OrderSimplifyVO> searchOrders(
            @RequestParam(name = "page", required = false, defaultValue = "0")
            @Min(value = 0, message = "{page.number.min}") Integer page,
            @RequestParam(name = "count", required = false, defaultValue = "10")
            @Min(value = 1, message = "{page.count.min}")
            @Max(value = 30, message = "{page.count.max}") Integer count,
            @RequestParam(name = "keyword", required = false) String keyword,
            @RequestParam(name = "start", required = false) Date start,
            @RequestParam(name = "end", required = false) Date end
    ) {
        com.baomidou.mybatisplus.core.metadata.IPage<OrderDO> iPage = orderService.search(page, count, keyword, start, end);
        List<OrderSimplifyVO> orderSimplifyVOList = orderService.convertFromDO(iPage.getRecords());
        return PageUtil.build(iPage, orderSimplifyVOList);
    }

    // ==================== 原有VipOrderController功能 ====================

    /**
     * 获取订单列表（支持类型过滤）
     */
    @GetMapping("/list")
    @GroupRequired
    @PermissionMeta("查询订单列表")
    public PageResponseVO<VipOrderVO> getOrderList(
            @RequestParam(name = "page", defaultValue = "0")
            @Min(value = 0, message = "{page.number.min}") Integer page,
            @RequestParam(name = "count", defaultValue = "10")
            @Min(value = 1, message = "{count.min}")
            @Max(value = 30, message = "{count.max}") Integer count,
            @RequestParam(name = "status", required = false) String status,
            @RequestParam(name = "keyword", required = false) String keyword,
            @RequestParam(name = "type", required = false) String type) {
        
        return orderService.getOrderPage(page, count, status, keyword, type);
    }

    /**
     * 获取订单详情（增强版）
     */
    @GetMapping("/{id}")
    @GroupRequired
    @PermissionMeta("查询订单详情")
    public VipOrderVO getOrderDetailEnhanced(@PathVariable @Positive(message = "{id.positive}") Long id) {
        return orderService.getOrderDetail(id);
    }

    /**
     * 获取待支付审核的订单列表
     */
    @GetMapping("/payment-pending")
    @GroupRequired
    @PermissionMeta("查询待支付审核订单")
    public PageResponseVO<VipOrderPaymentConfirmVO> getPaymentPendingOrders(
            @RequestParam(name = "page", defaultValue = "0")
            @Min(value = 0, message = "{page.number.min}") Integer page,
            @RequestParam(name = "count", defaultValue = "10")
            @Min(value = 1, message = "{count.min}")
            @Max(value = 30, message = "{count.max}") Integer count,
            @RequestParam(name = "status", defaultValue = "pending") String status) {
        
        return orderService.getPaymentPendingOrders(page, count, status);
    }

    /**
     * 获取订单支付审核详情
     */
    @GetMapping("/payment-detail/{id}")
    @GroupRequired
    @PermissionMeta("查询支付审核详情")
    public VipOrderPaymentConfirmVO getPaymentDetail(@PathVariable @Positive(message = "{id.positive}") Long id) {
        return orderService.getPaymentDetail(id);
    }

    /**
     * 确认订单支付
     */
    @PostMapping("/confirm-payment/{id}")
    @GroupRequired
    @PermissionMeta("确认支付")
    public Map<String, Object> confirmPayment(
            @PathVariable @Positive(message = "{id.positive}") Long id,
            @RequestBody @Validated VipOrderPaymentConfirmDTO dto) {
        
        orderService.confirmPayment(id, dto);
        Map<String, Object> result = new HashMap<>();
        result.put("message", "支付确认成功");
        return result;
    }

    /**
     * 拒绝订单支付
     */
    @PostMapping("/reject-payment/{id}")
    @GroupRequired
    @PermissionMeta("拒绝支付")
    public Map<String, Object> rejectPayment(
            @PathVariable @Positive(message = "{id.positive}") Long id,
            @RequestBody @Validated VipOrderPaymentConfirmDTO dto) {
        
        orderService.rejectPayment(id, dto);
        Map<String, Object> result = new HashMap<>();
        result.put("message", "支付拒绝成功");
        return result;
    }

    /**
     * 获取订单支付审核统计
     */
    @GetMapping("/payment-stats")
    @GroupRequired
    @PermissionMeta("查询支付审核统计")
    public Map<String, Object> getPaymentStats() {
        return orderService.getPaymentStats();
    }

    /**
     * 批量确认支付
     */
    @PostMapping("/batch-confirm-payment")
    @GroupRequired
    @PermissionMeta("批量确认支付")
    public Map<String, Object> batchConfirmPayment(@RequestBody Map<String, Object> request) {
        @SuppressWarnings("unchecked")
        List<Long> orderIds = (List<Long>) request.get("orderIds");
        String remark = (String) request.get("remark");
        
        orderService.batchConfirmPayment(orderIds, remark);
        Map<String, Object> result = new HashMap<>();
        result.put("message", "批量确认支付成功");
        return result;
    }

    /**
     * 批量拒绝支付
     */
    @PostMapping("/batch-reject-payment")
    @GroupRequired
    @PermissionMeta("批量拒绝支付")
    public Map<String, Object> batchRejectPayment(@RequestBody Map<String, Object> request) {
        @SuppressWarnings("unchecked")
        List<Long> orderIds = (List<Long>) request.get("orderIds");
        String remark = (String) request.get("remark");
        
        orderService.batchRejectPayment(orderIds, remark);
        Map<String, Object> result = new HashMap<>();
        result.put("message", "批量拒绝支付成功");
        return result;
    }
}
